package com.anonymous.community;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;

import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.CreatePostRequest;
import com.anonymous.community.api.model.CreatePostResponse;
import com.anonymous.community.databinding.ActivityPublishBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.anonymous.community.utils.TokenManager;
import com.tencent.bugly.crashreport.CrashReport;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 发帖Activity
 * 实现匿名发帖功能
 */
public class PublishActivity extends BaseActivity {

    private ActivityPublishBinding binding;
    private ApiService apiService;
    private boolean isPublishing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPublishBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        apiService = ApiClient.getApiService();

        setupViews();
        setupBackPressedHandler();
    }

    private void setupViews() {
        // 返回按钮
        binding.btnBack.setOnClickListener(v -> {
            finish();
            overridePendingTransition(R.anim.slide_in_left_dashboard, R.anim.slide_out_right_dashboard);
        });

        // 发布按钮
        binding.btnPublish.setOnClickListener(v -> publishPost());

        // 内容输入监听
        binding.etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateCharCount(s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // 初始化字数统计
        updateCharCount(0);
    }

    /**
     * 更新字数统计
     */
    private void updateCharCount(int count) {
        binding.tvCharCount.setText(String.format("%d/5000", count));
        
        // 字数超限时变红
        if (count > 5000) {
            binding.tvCharCount.setTextColor(getResources().getColor(R.color.error));
        } else {
            binding.tvCharCount.setTextColor(getResources().getColor(R.color.colorTextSecondary));
        }
    }

    /**
     * 发布帖子
     */
    private void publishPost() {
        if (isPublishing) return;

        String content = binding.etContent.getText().toString().trim();

        // 验证内容
        if (content.isEmpty()) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }

        if (content.length() < 1 || content.length() > 5000) {
            Toast.makeText(this, "内容长度需在1-5000字符之间", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查登录状态
        String token = TokenManager.getToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 显示加载状态
        showLoading(true);
        isPublishing = true;

        // 创建请求
        CreatePostRequest request = new CreatePostRequest(content);

        // 调用API
        apiService.createPost(token, request)
                .enqueue(new Callback<CreatePostResponse>() {
                    @Override
                    public void onResponse(Call<CreatePostResponse> call, Response<CreatePostResponse> response) {
                        isPublishing = false;
                        showLoading(false);

                        if (response.isSuccessful() && response.body() != null) {
                            // 发布成功
                            CrashReport.postCatchedException(new Exception("Event: Publish Post Success"));
                            
                            Toast.makeText(PublishActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                            
                            // 设置结果并返回
                            setResult(RESULT_OK);
                            finish();
                            overridePendingTransition(R.anim.slide_in_left_dashboard, R.anim.slide_out_right_dashboard);
                        } else {
                            // 发布失败
                            String errorMessage = extractErrorMessage(response);
                            if (errorMessage == null || errorMessage.isEmpty()) {
                                errorMessage = "发布失败，请稍后重试";
                            }
                            Toast.makeText(PublishActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CreatePostResponse> call, Throwable t) {
                        isPublishing = false;
                        showLoading(false);
                        Toast.makeText(PublishActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 显示/隐藏加载状态
     */
    private void showLoading(boolean show) {
        binding.btnPublish.setEnabled(!show);
        binding.etContent.setEnabled(!show);
        binding.progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    /**
     * 从错误响应中提取错误信息
     */
    private String extractErrorMessage(Response<?> response) {
        try {
            if (response != null && response.errorBody() != null) {
                String raw = response.errorBody().string();
                if (raw != null && !raw.isEmpty()) {
                    try {
                        org.json.JSONObject obj = new org.json.JSONObject(raw);
                        if (obj.has("error")) {
                            return obj.optString("error");
                        }
                    } catch (Exception jsonEx) {
                        return raw;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        return null;
    }

    /**
     * 设置系统返回键处理
     */
    private void setupBackPressedHandler() {
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                finish();
                overridePendingTransition(R.anim.slide_in_left_dashboard, R.anim.slide_out_right_dashboard);
            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        overridePendingTransition(R.anim.slide_in_left_dashboard, R.anim.slide_out_right_dashboard);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "发布页";
    }
}
